#!/bin/sh
CURRENT_DIR="$(cd "$(dirname $0)"; pwd)"
CONFIG_DIR=$CURRENT_DIR/configs

ENV_FILE=$CURRENT_DIR/.env
if [ -f "$ENV_FILE" ]; then
  source $ENV_FILE
else
  touch $ENV_FILE
fi

readenv() {
  KEY=$1
  EXPRESS="echo \$$KEY"
  VALUE=`eval $EXPRESS`
  if [ -z "$VALUE" ]; then
    read -p "Please Input $KEY:" VALUE
    sed -i '' "/"$KEY"/d" $ENV_FILE
    echo "$KEY=$VALUE" >> $ENV_FILE
    EXPRESS="$KEY=$VALUE"
    eval $EXPRESS
  fi
}

upload() {
  FILE=$1
  APPID=`cat $FILE | jq .extAppid | awk -F "\"" '{print $2}'`
  curl -F "file=@$FILE" -F username=$ADMIN_USER -F password=$ADMIN_PWD -F appid=$APPID $DIANLI_HOST/westore/app/config
}

readenv 'DIANLI_HOST'
readenv 'ADMIN_USER'
readenv 'ADMIN_PWD'

cd $CONFIG_DIR

if [ $# -gt 0 ]; then
  file="$1.json"
  if [ -f "$file" ]; then
      upload $file
  else
      echo "file $file not exist"
  fi
else
  for file in `ls`; do
      upload $file
  done
fi